package nspel

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type OssConfig struct {
	AccessKeyId     string `json:"accessKeyId"`
	AccessKeySecret string `json:"accessKeySecret"`
	EndPoint        string `json:"endPoint"`
	PicBucketName   string `json:"picBucketName"`
	VideoBucketName string `json:"videoBucketName"`
	SignedLife      int64  `json:"signedLife"`
}

var ossConfig OssConfig
var ossClient *oss.Client
var videoBucket *oss.Bucket

func configOss() {
	loadConfigJson("config/oss.json", &ossConfig)
	var err error
	ossClient, err = oss.New(ossConfig.EndPoint, accessKeyId, accessKeySecret)
	if err != nil {
		Error(err)
		panic(err)
	}
	videoBucket, err = ossClient.Bucket(ossConfig.VideoBucketName)
	if err != nil {
		Error(err)
		panic(err)
	}
}

func GetDownloadSignUrl(objectName string) (signedURL string, err error) {
	signedURL, err = videoBucket.SignURL(objectName, oss.HTTPGet, ossConfig.SignedLife)
	if err != nil {
		videoBucket, err = ossClient.Bucket(ossConfig.VideoBucketName)
		if err != nil {
			ossClient, err = oss.New(ossConfig.EndPoint, accessKeyId, accessKeySecret)
			if err != nil {
				return
			}
			videoBucket, err = ossClient.Bucket(ossConfig.VideoBucketName)
			if err != nil {
				return
			}
		}
		signedURL, err = videoBucket.SignURL(objectName, oss.HTTPGet, ossConfig.SignedLife)
	}
	return
}
